//
//  zhuye.m
//  kankanVideo
//
//  Created by wangbo on 7/2/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "zhuye.h"
#import "GANTracker.h"

@implementation zhuye
@synthesize pc,sv,pageImageView,lblPage,btntidy;
@synthesize lview;
@synthesize channelViewController;

static int offsetx=50;
static int offsety=50;
static int paddingx=50;
static int paddingy=50;
static int nw=160;
static int nh=160;

-(void)viewWillAppear:(BOOL)animated{
    NSError *error;
    if (![[GANTracker sharedTracker] trackPageview:@"看看吧ipad-首页"
                                         withError:&error]) {
        NSLog(@"error in trackPageview");
    }
    NSLog(@"guilder_view_will_appear");
}

-(void)emptyListItem{
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)dealloc{
    [pc release];
    [sv release];
    [pageImageView release];
    [lblPage release];
    [btntidy release];
    [super dealloc];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    //coreData=[[MyCoreData alloc]initWithTableName:@"IndexData"];
    // Do any additional setup after loading the view from its nib.
    [btntidy setHidden:YES];
    [sv setContentSize:CGSizeMake(1000, 460)];
    sv.delegate=self;
    //pc=[[UIPageControl alloc]init];
    //pc.numberOfPages=3;
    //[pc addTarget:self action:@selector(pageTurn:) forControlEvents:UIControlEventValueChanged];
    //lview=[[library alloc]init];
    //lview.delegate=self;
    [self initItemWithCache];
    [self tidyItem];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSLog(@"============scrollViewDidEndDecelerating================");
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDidStopSelector:@selector(animationComplete)];
    //lblPage.text=scrollView.contentOffset.x/320;
    NSLog(@"%d",((int)scrollView.contentOffset.x/1024)+1);
    lblPage.text=[NSString stringWithFormat:@"%d",((int)scrollView.contentOffset.x/1024)+1];
    //sv.contentOffset=CGPointMake(320*nowPage,0);
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:pageImageView cache:YES];
    [UIView commitAnimations];
    
    //lblPage.text=[NSString stringWithFormat:@"%d",((int)sv.contentOffset.x/320)+1];
    [self.view setNeedsDisplay];
}

-(IBAction)refreshIndex:(id)sender{
    /*UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"刷新首页" message:@"您是否确定刷新首页" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil];
    [alert show];
    [alert release];*/
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%@:%d",alertView.title,buttonIndex);
    if (buttonIndex==0) {
        
    }
}

-(void)moveView:(int)direction{
    if (direction==-1) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDidStopSelector:@selector(animationComplete)];
        [lview.view setFrame:CGRectMake(1024, 0, 500, 748)];
        [UIView commitAnimations];
    }
}

-(IBAction)gotoLibrary:(id)sender{
    if(!lview){
        self.lview=[[library alloc]init];
        lview.delegate=self;
        [self.view addSubview:lview.view];
        [lview release];
            NSError *error;
            if (![[GANTracker sharedTracker] trackPageview:@"看看吧ipad-订阅页"
                                                 withError:&error]) {
                NSLog(@"error in trackPageview");
            }
            NSLog(@"guilder_view_will_appear");
        
    }
    NSLog(@"gotoLibrary");
    [lview.view setFrame:CGRectMake(1024, 0, 500, 748)];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDidStopSelector:@selector(animationComplete)];
    //sv.contentOffset=CGPointMake(320*nowPage,0);
    [lview.view setFrame:CGRectMake(1024-500, 0, 500, 748)];
    [UIView commitAnimations];
    //[self.navigationController pushViewController:lview animated:YES];
    //NSLog(@"gotolibrary_addeditem_retaincount:%d",addeditem.retainCount);
}

-(void) pageTurn:(UIPageControl *)sender{
    NSLog(@"============pageTurn================");
    //int nowPage=sender.currentPage;
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDidStopSelector:@selector(animationComplete)];
    //sv.contentOffset=CGPointMake(320*nowPage,0);
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:pageImageView cache:YES];
    [UIView commitAnimations];
    //[self updateDots];
    //[self showAlert:@"aaaa"];
    
    /*[UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    UIView */
}

-(void)showVideoList:(NSString *)classid withTitle:(NSString *)theTitle{
    //if(!channelViewController)channelViewController=[[ChannelDetailViewController alloc]init];
    if(!padPlayerViewController)padPlayerViewController=[[IpadPlayerViewController alloc]init];
    if ([classid isEqualToString:@"0"]) {
        //if(!uploadViewController)uploadViewController=[[UploadVideoViewController alloc]init];
        //[self.navigationController pushViewController:uploadViewController animated:YES];
    }else if([classid isEqualToString:@"-1"]){
        [self gotoLibrary:nil];
    }else{
        [padPlayerViewController showVideoList:[NSMutableArray arrayWithObjects:classid,theTitle, nil]];
        //[self.navigationController pushViewController:padPlayerViewController animated:YES];
        [self presentModalViewController:padPlayerViewController animated:YES];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight||interfaceOrientation==UIInterfaceOrientationLandscapeLeft);
}

-(void)modifyListItem:(int)actionType withParam:(NSMutableArray *)param{
    NSLog(@"modify:%d and param:%@",actionType,param);
    if(actionType==1){
        [[MyCoreData shareInstance]insertWithParam:param];
        ListItem *item=[[ListItem alloc]initWithFrame:CGRectMake(0,0, nw, nh) withParam:param];
        item.delegate=self;
        [sv addSubview:item];
        [item release];
    }else if(actionType==-1){
        [[MyCoreData shareInstance]deleteWithParam:param];
        for (ListItem *item in [sv subviews]) {
            if([item isKindOfClass:[ListItem class]]){
                if ([[item classid] isEqualToString:[param objectAtIndex:0]]) {
                    [item removeFromSuperview];
                    break;
                }
            }
        }
    }
    [self tidyItem];
}
-(void)refreshCache{
    //NSLog(@"addeditem_retaincount:%d",addeditem.retainCount);
    [[MyRequest shareInstance]loaddataWithURL:@"http://interface.kankanews.com/kkapi/mobile/padapi.php?m=clistphone&c=ios" forObject:self];
    //[[MyRequest shareInstance]loaddataWithURL:@"http://interface.kankanews.com/kkapi/mobile/mobileapi.php?m=clistphone" forObject:self];
    
}
-(void)requestFinishedHandler:(ASIHTTPRequest*)request{
    if(request.responseStatusCode==200){
        NSArray *serverArray=[XMLParser parseCategoryList:request.responseData];
        BOOL fg=NO;
        NSArray *cacheArray=[[MyCoreData shareInstance]query];
        for (int i=0; i<serverArray.count; i++) {
            fg=NO;
            for (int j=0; j<cacheArray.count; j++) {
                IndexData *_cacheData=[cacheArray objectAtIndex:j];
                if ([_cacheData.classid isEqualToString:[[serverArray objectAtIndex:j] objectAtIndex:5]]) {
                    //update cache
                    fg=YES;
                    break;
                }
            }
            if(!fg){
                NSArray *serverData=[serverArray objectAtIndex:i];
                if ((![[serverData objectAtIndex:7] isEqualToString:@"0"])||(![[serverData objectAtIndex:8] isEqualToString:@"0"])) {
                    //insert cache
                    NSMutableArray *insertedData=[[NSMutableArray alloc]init];
                    [insertedData addObject:[serverData objectAtIndex:5]];
                    [insertedData addObject:[serverData objectAtIndex:0]];
                    [insertedData addObject:[serverData objectAtIndex:3]];
                    [insertedData addObject:[serverData objectAtIndex:2]];
                    [insertedData addObject:[serverData objectAtIndex:7]];
                    [insertedData addObject:[serverData objectAtIndex:8]];
                    [[MyCoreData shareInstance]insertWithParam:insertedData];
                }
            }
        }
        [self initItemWithCache];
        [self tidyItem];
        AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        [app hideAlert];
    }
}

-(void)clickMenu:(int)_operationid{
    if(_operationid==1){
        if(!hvc)hvc=[[HelperVierController alloc]init];
         [self presentModalViewController:hvc animated:YES];
    }else if(_operationid==2){
        
    }
}
-(IBAction)gotoSetting:(id)sender{
    /*if(!settingView)settingView=[[settingViewController alloc]init];
    [self.navigationController pushViewController:settingView animated:YES];
     */
    if(!settingView){
        settingView=[[settingViewController alloc]init];
        settingView.delegate=self;
    }
    [self.view addSubview:settingView.view];
        NSError *error;
        if (![[GANTracker sharedTracker] trackPageview:@"看看吧ipad-设置页"
                                             withError:&error]) {
            NSLog(@"error in trackPageview");
        }
        NSLog(@"guilder_view_will_appear");
    [settingView.view setFrame:CGRectMake(1024, 0, 500, 748)];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDidStopSelector:@selector(animationComplete)];
    //sv.contentOffset=CGPointMake(320*nowPage,0);
    [settingView.view setFrame:CGRectMake(1024-500, 0, 500, 748)];
    [UIView commitAnimations];
}
-(void)initItemWithCache{
    NSArray *arr=[[MyCoreData shareInstance]query];
    int cc=[arr count];
    if(cc==0){
        AppDelegate *app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
        [app showAlert:@"正在加载"];
        [self refreshCache];
        return;
    }
    for(int i=0;i<cc;i++){
        IndexData *obj=[arr objectAtIndex:i];
        NSMutableArray *barray=[NSMutableArray arrayWithCapacity:5];
        [barray addObject:[obj classid]];
        [barray addObject:[obj title]];
        [barray addObject:[obj titlepic]];
        [barray addObject:[obj bigpic]];
        [barray addObject:[obj isgood]];
        ListItem *item=[[ListItem alloc]initWithFrame:CGRectMake(0,0, nw, nh) withParam:barray];
        //ListItem *item=[[ListItem alloc]initWithFrame:CGRectMake(0,0, nw, nh) withImageURL:[obj titlepic]];
        item.delegate=self;
        [sv addSubview:item];
        
        NSLog(@"%d",sv.subviews.count);
        
        [item release];
        //NSLog(@"iiiittteeemm_:%d",item.retainCount);
        
        
        
    }
    itemcount=cc;
}

-(IBAction)mytidy:(id)sender{
    [self tidyItem];
    //NSLog(@"aftertidy_addeditem_retaincount1:%d",addeditem.retainCount);
}
-(void)tidyItem{
    //NSLog(@"addeditem_retaincount1:%d",addeditem.retainCount);
    //BOOL isfirst=YES;
    int lines=0;
    int ccc=0;
    int cpage=0;
    int rows=0;
    int cols=0;
    itemcount=0;
    for (ListItem *item in [sv subviews]) {
        if ([item isKindOfClass:[ListItem class]]) {
            itemcount++;
            NSLog(@"listitem:%d",item.retainCount);
            [item setFrame:CGRectMake((cpage*1024)+offsetx+(paddingx+nw)*cols, offsety+rows*(nh+paddingy), nw, nh)];
            cols++;
            ccc++;
            if (cols==4) {
                cols=0;
                rows++;
            }
            if(ccc%12==0&&ccc!=0){
                lines=0;
                cpage++;
                rows=0;
            }
        }
    }
    //NSLog(@"addeditem_retaincount5:%d",addeditem.retainCount);
    //[sv setContentSize:CGSizeMake(320*((int)(((itemcount+1)/8)+0.5)), 460)];
    //itemcount++;
    int pp=ceil((double)(itemcount)/12);
    [sv setContentSize:CGSizeMake(1024*pp, 748)];
    pc.numberOfPages=pp;
    lblPage.text=[NSString stringWithFormat:@"%d",((int)sv.contentOffset.x/1024)+1];
    //NSLog(@"page_count:%d and itemcount:%d",pp,itemcount);
    //if(lines>3)[self.sv setContentSize:CGSizeMake(320, lines*(nh+paddingy))];
}

@end
